﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BookExchange.Business;
using BookExchange.CustomClass.Base;
using BookExchange.ODataService;
using BookExchange.Utility;
using System.Linq.Expressions;
using BookExchange.ViewModel;
using BookExchange.Configuration;

namespace BookExchange
{
    public partial class Search : BasePage
    {
        //public enum SearchBy
        //{
        //    None = 0,
        //    Name = 1,
        //    Category = 2,
        //    AllPost = 3,
        //    AllRequest = 4,
        //    User = 5
        //};

        #region formatString
        private string _formatDate = "{0:" + AppConfiguration.Instance.DateFormat + "}";
        private string _formatQuantity = "{0:" + AppConfiguration.Instance.IntegerFormat + "}";
        private string _formatPrice1 = "{0:" + AppConfiguration.Instance.CurrencyFormat + "}";
        private string _formatPrice2 = "{0:" + AppConfiguration.Instance.CurrencyFormat + "}";


        public string formatDate
        {
            get { return _formatDate; }

        }
        public string formatQuantity
        {
            get { return _formatQuantity; }
        }
        public string formatPrice1
        {
            get { return _formatPrice1; }
        }
        public string formatPrice2
        {
            get { return _formatPrice2; }
        }
        #endregion

        
        
        private string queryStringRequest = "allrequest=1";
        private string queryStringPost = "allpost=1";
         private RequestBusiness requestBus;

        static private string queryString;
        static private int itemPerPage = AppConfiguration.Instance.MaxItemPerPage; 
        static IQueryable<ODataService.Request> queryRequest;
        static IQueryable<ODataService.Request> queryPost;
        static int requestCount;
        static int postCount;
        public Search()
            : base()
        {
            requestBus = new RequestBusiness(); 
        }

        /*
            Có thể nhận vao các giá trị sau và trả về
            1. search.aspx?name=dong%ga   search theo tên sách
            2. search.aspx?cat=12   search theo category
            3. search.aspx?allpost=1   search tất cả các Request có type = P, nhớ phân trang, pagesize = AppConstant.PageSize
            4. search.aspx?allrequest=1   search tất cả các Request có type= R, nhớ phân trang, pagesize = AppConstant.PageSize

            Kết quả search được sắp sếp theo ngày, mới trước, cũ sau
         
            active current page css class : nta-entry-page-active
        */
        /*
* Nếu không có queryString allpost và allrequest thì tách riêng kết quả search ra 
* phần RequestType.Post riêng và RequestType.Request riêng
* Nếu chỉ có queryString allpost thì chỉ search theo RequestType.Post
* Nếu chỉ có queryString allrequest thì chỉ search theo RequestType.Post
*/

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                return;
            }
            bool flag = false; 
            string searchText = string.Empty;
            queryString = Request.Url.Query;
            IQueryable<ODataService.Request> query = requestBus.GetQueryDefault();


            //check and get query of MemberCode field
            if (!string.IsNullOrEmpty(searchText = Request.QueryString["myrequest"]) && searchText == "1")//search all by user
            {

                if (Session[AppConstant.CurrentUser] != null)
                {
                    flag = true;
                    query = requestBus.GetQueryFilterUser(query, CurrentMember.MemberCode );
                }
                else
                {
                    //Member chưa đăng nhập;
                    return;
                }
            }

            //check and get query of CategoryCode field
            int category = 0;
            if (int.TryParse(Request.QueryString["cat"], out category))//search by category
            {
                flag = true;
                query = requestBus.GetQueryFilterCategory(query, category );
            }

            //check and get query of Name field
            if (!string.IsNullOrEmpty(searchText = Request.QueryString["name"]))//search by name
            {
                flag = true;
                query = requestBus.GetQueryFilterName(query, searchText );
            }


            //check RequestType field
            if (!string.IsNullOrEmpty(searchText = Request.QueryString["allpost"]) && searchText == "1" ||
                !string.IsNullOrEmpty(searchText = Request.QueryString["allrequest"]) && searchText == "1")
            {
                Response.Redirect("SearchAll" + queryString);
            }
            else
            {
                if (flag)
                {
                    //get query RequestType
                    queryRequest = requestBus.GetQueryFilterRequestType(query, RequestType.Request );
                    queryPost = requestBus.GetQueryFilterRequestType(query, RequestType.Post );



                    //Post
                    postCount = requestBus.GetCountActiveRequest(queryPost);
                    lblPostQty.Text = postCount.ToString() + string.Empty;

                    AspNetPagerPost.RecordCount = postCount;
                    AspNetPagerPost.PageSize = itemPerPage;

                    if (postCount <= itemPerPage)
                        hplRealAllPost.Visible = false;
                    else
                        hplRealAllPost.NavigateUrl = "~/SearchAll.aspx" + queryString + "&" + queryStringPost;

                    BindDataPost();


                    //Request  
                    requestCount = requestBus.GetCountActiveRequest(queryRequest);
                    lblRequestQty.Text = requestCount.ToString() + string.Empty;

                    AspNetPagerRequest.RecordCount = requestCount;
                    AspNetPagerRequest.PageSize = itemPerPage;

                    if (requestCount <= itemPerPage)
                        hplReadAllRequest.Visible = false;
                    else
                        hplReadAllRequest.NavigateUrl = "~/SearchAll.aspx" + queryString + "&" + queryStringRequest;

                    BindDataRequest();
                }
                else
                    hplReadAllRequest.Visible = hplRealAllPost.Visible = false;
            }



        }

        private void BindDataPost()
        {
            int skipItem = AspNetPagerPost.StartRecordIndex - 1;

            List<Request> postList = requestBus.GetListActiveRequest(queryPost, skipItem, itemPerPage);
            repPost.DataSource = postList;
            repPost.DataBind(); 
        }

        private void BindDataRequest()
        {
            int skipItem = AspNetPagerRequest.StartRecordIndex - 1;

            List<Request> requestList = requestBus.GetListActiveRequest(queryRequest, skipItem, itemPerPage);
            repRequest.DataSource = requestList;
            repRequest.DataBind();
        }

                    

        protected void AspNetPagerPost_PageChanged(object src, EventArgs e)
        {
            //if current page > 2
            if (AspNetPagerPost.StartRecordIndex > itemPerPage)
            {
                Session["skip"] = AspNetPagerPost.StartRecordIndex - 1; 
                Session["PostCount"] = postCount;
                Session.Timeout = 5;
                Response.Redirect("SearchAll" + queryString + "&" + queryStringPost);
            }
            else
                BindDataPost();
        }


        protected void AspNetPagerRequest_PageChanged(object src, EventArgs e)
        {
            //if current page > 2
            if (AspNetPagerRequest.StartRecordIndex > itemPerPage)
            {
                Session["skip"] = AspNetPagerRequest.StartRecordIndex - 1;
                Session["RequestCount"] = requestCount;
                Session.Timeout = 5;
                Response.Redirect("SearchAll" + queryString + "&" + queryStringRequest);
            }
            else
                BindDataRequest();
        } 

        public class Paging
        {
            public string Link { get; set; }
            public string ActiveClass { get; set; }
        }
    }
}